﻿using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EMC.VISITOR.Core
{
    public class ResilienceClientFactory
    {
        private ILogger<ResilienceHttpClient> _logger;
        private IHttpContextAccessor _httpContextAccessor;
        /// <summary>
        /// 重试次数
        /// </summary>
        private int _retryCount;
        /// <summary>
        /// 熔断之前允许的异常次数
        /// </summary>
        private int _exceptionCountAllowedBeforeBreaking;
        public ResilienceClientFactory(ILogger<ResilienceHttpClient> _logger,
            IHttpContextAccessor _httpContextAccessor,
            int _retryCount,
            int _exceptionCountAllowedBeforeBreaking
            )
        {
            this._logger = _logger;
            this._httpContextAccessor = _httpContextAccessor;
            this._retryCount = _retryCount;
            this._exceptionCountAllowedBeforeBreaking = _exceptionCountAllowedBeforeBreaking;
        }

        public ResilienceHttpClient GetResilienceHttpClient() => new ResilienceHttpClient("", origin => CreatePolicy(origin), _logger, _httpContextAccessor);

        /// <summary>
        ///  使用Polly 对接口重试等操作
        /// </summary>
        /// <param name="origin"></param>
        /// <returns></returns>
        private Policy[] CreatePolicy(string origin)
        {
            return new Policy[] { };
            //return new Policy[] { 
            //    // 当请求出现 HttpRequestException 异常时
            // Policy.Handle<HttpRequestException>()
            //    // 等待并且重试
            // .WaitAndRetryAsync(
            //      // _retryCount:重试次数
            //     _retryCount,
            //     // 重试的间隔时间
            // retryAttempt=>TimeSpan.FromSeconds(Math.Pow(2,retryAttempt)),
            //    // 错误捕获
            // (exception,timeSpan,retryCount,context)=>{
            //     var msg=$"第 {retryCount} 次重试 "+
            //             $"of {context.PolicyKey} "+
            //             $"at {context.ExecutionKey}, "+
            //             $"due to: {exception}";
            //      _logger.LogWarning(msg);
            //     _logger.LogDebug(msg);
            // }),

            // // 当请求出现 HttpRequestException 时
            // Policy.Handle<HttpRequestException>()
            // // 熔断
            // .CircuitBreakerAsync(
            //_exceptionCountAllowedBeforeBreaking,
            // TimeSpan.FromMinutes(1),
            // (exception,duration)=>
            // {
            //     _logger.LogTrace("熔断器打开");
            // },
            // ()=>
            // {
            //     _logger.LogTrace("熔断器关闭");
            // }
            // )
            //};
        }
    }
}
